<template>
  <div class="flex flex-wrap min-h-10 items-center">
    <template v-if="!loading">
      <template v-if="dataSource.length === 0"> <div class="pt-3 text-gray-300">暂无数据</div> </template>
      <template v-else>
        <div v-for="(tag, index) in dataSource" :key="tag" :class="tagWidth" class="pr-2">
          <a-checkable-tag :key="tag" v-model:checked="selectStatus[index]" class="tag-item" :class="tagClass" @change="handleChange(tag, $event)">
            <slot name="renderItem" :item="tag"></slot>
          </a-checkable-tag>
        </div>
      </template>
    </template>
    <a-skeleton-button v-else class="mt-2" active block />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'

const emit = defineEmits(['update:value', 'select'])

const props = defineProps({
  dataSource: {
    type: Array,
    default: () => []
  },
  value: {
    type: [String, Array],
    default: () => []
  },
  multiple: {
    type: Boolean,
    default: false
  },
  tagClass: {
    type: String,
    default: ''
  },
  tagWidth: {
    type: String,
    default: ''
  },
  tagKey: {
    type: String,
    default: ''
  }
})
const loading = ref(true)
const selectStatus = ref([])
watch(
  () => props.dataSource.length,
  (val) => {
    loading.value = val === 0
  },
  {
    immediate: true
  }
)
watch(
  () => props.value,
  (val) => {
    if (props.multiple) {
      selectStatus.value = props.dataSource.map((item) => {
        return val.some((v) => item[props.tagKey] === v)
      })
    } else {
      selectStatus.value = props.dataSource.map((item) => {
        return item[props.tagKey] === val
      })
    }
  },
  {
    immediate: true
  }
)
const handleChange = (tag, isCheck) => {
  if (props.multiple) {
    const value = props.dataSource.filter((item, index) => selectStatus.value[index]).map((item) => item[props.tagKey])
    emit('update:value', isCheck ? value : [])
    emit('select', isCheck ? value : [], isCheck ? tag : [{}])
  } else {
    const value = isCheck ? tag[props.tagKey] : ''
    const selectTag = isCheck ? tag : {}
    emit('update:value', value)
    emit('select', value, selectTag)
  }
}
</script>
<style lang="less" scoped>
.tag-item {
  width: 100%;
  height: 32px;
  margin-top: 4px;
  margin-bottom: 4px;
  padding: 4px 8px;
  font-size: 14px;
  text-align: center;
  background-color: var(--thin-color);
  &:hover:not(.ant-tag-checkable-checked) {
    background-color: var(--secondary-color);
    border: 1px solid var(--primary-color);
  }
}
.ant-tag-checkable-checked {
  color: #fff;
  background-color: var(--primary-color);
}
</style>
